import hashlib
import hmac
import random

from django.conf import settings
from django.db import models

#Python 2.4 compatibility
sha256 = hashlib.sha256
try:
    getattr(sha256, 'new')
except AttributeError:
    from HashlibProxy import HashlibProxy
    sha256 = HashlibProxy(hashlib.sha256)
    
class Channel(models.Model):
    class Meta:
        app_label = 'chat'
    
    hash = models.CharField(max_length=64, unique=True, primary_key=True, editable=False)
    name = models.CharField(max_length=512, blank=True)

    @classmethod
    def prune_channels(cls):
        # TODO: Implement Me
        pass

    def __unicode__(self):
        return u"%s %s" % (self.name, self.hash)

    def save(self, *args, **kwargs):              
        if len(self.hash) == 0:
            self.hash = hmac.new(settings.SECRET_KEY, str(random.random()) + settings.SALT_KEY, sha256).hexdigest()
            
        super(Channel, self).save(*args, **kwargs)